<template>
    <div class="order-sum">
        <div>
            <span class="down-execel">
                <Poptip v-model="showFilter" placement="bottom-end">
                    <i class="el-icon-search poptip-condition-add"></i>
                    <a href="javascript:;" class='poptip-condition-add'>列表查找</a>
                    <div slot="content">
                        <Poptip v-model="showFilterCondition" placement="bottom-start" class='poptip-condition'>
                            <i class="el-icon-plus"></i>
                            <a href="javascript:;">添加过滤条件</a>
                            <div slot="content" class="condition-list">
                                <ul>
                                    <li
                                        v-for="(item, index) in selectHead"
                                        :key="index"
                                        class='poptip-condition-item'
                                        @click="addFilterCondition(item)">
                                        {{item.label}}
                                    </li>
                                </ul>
                            </div>
                        </Poptip>
                        <el-form :model="conditionForm" @submit.native.prevent ref="conditionForm" label-width="120px" class="demo-dynamic">
                            <el-form-item
                                v-for="(condition, index) in conditionForm.condition"
                                :label="condition.label"
                                :key="condition.key"
                                :prop="'condition.' + index + '.value'"
                                :rules="{required: true, message: condition.label + '不能为空', trigger: 'blur'}">
                                <el-select
                                    v-if='condition.label === "流程人员"'
                                    v-model="condition.value"
                                    placeholder="请选择流程人员"
                                    size="small"
                                    filterable
                                >
                                    <el-option
                                        v-for="item in processOptions"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    ></el-option>
                                </el-select>
                                <el-select
                                    v-else-if='condition.label === "代理人"'
                                    v-model="condition.value"
                                    placeholder="请选择代理人"
                                    size="small"
                                    filterable
                                >
                                    <el-option
                                        v-for="item in agentOptions"
                                        :key="item.id"
                                        :label="item | agentNumAddName"
                                        :value="item.id"
                                    ></el-option>
                                </el-select>
                                <el-select
                                    v-else-if='condition.label === "代理人类型"'
                                    v-model="condition.value"
                                    placeholder="请选择代理人类型"
                                    size="small"
                                    filterable
                                >
                                    <el-option label='普通代理人' value="2"></el-option>
                                    <el-option label='VIP代理人' value="1"></el-option>
                                </el-select>
                                <el-date-picker
                                    v-model="condition.value"
                                    type="daterange"
                                    placeholder="选择日期"
                                    value-format="yyyy-MM-dd"
                                    size="small"
                                    :validate-event='false'
                                    v-else-if='condition.label === "时间选择"'>
                                </el-date-picker>
                                <el-input v-else size="small" v-model="condition.value" @keyup.enter.native="submitsearch('conditionForm')"></el-input>
                                <el-button @click.stop="removeDomain(condition)" size="mini">删除</el-button>
                            </el-form-item>
                        </el-form>

                        <div class="btns">
                            <el-button @click="submitsearch('conditionForm')" size="mini">查询</el-button>
                            <el-button @click="resetForm('conditionForm')" size="mini">重置</el-button>
                        </div>
                    </div>
                </Poptip>
            </span>
            <span class="down-execel" @click="exportExcel('结算统计表')">
				<i class="el-icon-download"></i> <a href="javascript:;">导出列表</a>
			</span>
        </div>
        <el-table
            :data="tableData"
            ref="order-table"
            border
            @sort-change='tableSortChange'
            @row-click="getDetail"
        >
            <el-table-column
                label="代理人"
                sortable="custom"
                prop="name"
                width="110"
                align="left"
                :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column
                label="总奖励金额(元)"
                prop="reward"
                sortable="custom"
                align="left"
                min-width="120"
                :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span class="finish">{{scope.row.reward}}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="总扣款金额(元)"
                sortable="custom"
                prop="deduction"
                min-width="120"
                align="left"
                :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span class="unfinish">{{scope.row.deduction}}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="未结算金额(元)"
                prop="unsettled"
                sortable="custom"
                min-width="120"
                align="left"
                :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span class="unfinish">{{scope.row.unsettled}}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="已结算金额(元)"
                prop="settled"
                sortable="custom"
                min-width="120"
                align="left"
                :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span class="finish">{{scope.row.settled}}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="总结算金额(元)"
                prop="total"
                min-width="120"
                sortable="custom"
                align="left"
                :show-overflow-tooltip="true">
            </el-table-column>
        </el-table>
        <pagination @paginationChange="pageChange" :total="total"></pagination>
        <!-- <sum-detail ref="sum-detail" @refresh="getTableData"></sum-detail> -->
        <settlementDetails ref="settlementDetails" @refresh="getTableData"></settlementDetails>
        <xyExcelExportTemplate ref='TerminalExportExcel'></xyExcelExportTemplate>
    </div>
</template>

<script>
import pagination from '~/components/pagination'
import sumDetail from './components/sum-detail'
import settlementDetails from './components/settlement-details'
import xyExcelExportTemplate from "~/components/ExcelExportTemplate";
export default {
    components: {
        pagination,
        sumDetail,
        settlementDetails,
        xyExcelExportTemplate
    },

    data() {
        return {
            tableData: [],
            current_page: 1,
            agentOptions: [],
            per_page: 25,
            total: 0,
            sort_params: {},
            search_params: {},
            showFilter: false,
            showFilterCondition: false,
            // 筛选条件
            conditionForm: {
                condition: []
            },
            selectHead: [
                {
                    label: '代理人',
                    props: 'agent_id'
                },
                {
                    label: '代理人类型',
                    props: 'agent_vip'
                }
            ],
        }
    },

    created() {
        this.getAllAgent()
        this.getTableData()
    },

    methods: {
        exportExcel(name) {
            let tabHandle = []
            this.$confirm('是否导出结算详情，导出的结算统计表则以结算详情的形式导出。', '提示', {
                confirmButtonText: '导出详情表',
                cancelButtonText: '导出当前表',
                distinguishCancelAndClose: true,
                center: true,
                }).then(() => {
                    tabHandle = [
                        '订单编号',
                        '拟申报专利名称',
                        '定稿名称',
                        '代理人',
                        '提交时间',
                        '定稿时间',
                        '第一发明人',
                        '身份证号',
                        '专利权人',
                        '发明人',
                        '联络人',
                        '邮箱',
                        '电话',
                        '订单耗时（天）',
                        // '流程状态',
                        '结算类型',
                        '结算金额（元）',
                        '扣款金额（元）',
                        '扣款原因',
                        '奖励金额（元）',
                        '奖励原因',
                        '合计（元）',

                    ]
                    let params = {
                        allPage: 2
                    }
                    this.$axios.get('/api/settlement/settlement_statistics_details', {
                        params: params
                    }).then(res => {
                        if (res.data.code == 200) {
                            if (res.data.data.length != 0) {
                                let exTableData = res.data.data
                                this.$refs.TerminalExportExcel.exportFinialSum(name, tabHandle, exTableData, 2)
                            } else {
                                this.$message({
                                    type: 'waring',
                                    message: '暂无数据导出。'
                                })
                            }
                        } else {
                            this.$message({
                                type: 'error',
                                message: res.data.message
                            })
                        }
                    })
                }).catch(action  => {
                    if (action === 'cancel') {
                        tabHandle = [
                            '代理人',
                            '总奖励金额（元）',
                            '总扣款金额（元）',
                            '未结算金额（元）',
                            '已结算金额（元）',
                            '总结算金额（元）',
                        ]
                        let params = {
                            allPage: 2
                        }
                        params = {...params, ...this.sort_params, ...this.search_params}
                        this.$axios.get('/api/settlement/settlement_statistics', {
                            params: params
                        }).then(res => {
                            if (res.data.code == 200) {
                                if (res.data.data.length != 0) {
                                    let exTableData = res.data.data
                                    this.$refs.TerminalExportExcel.exportFinialSum(name, tabHandle, exTableData, 1)
                                } else {
                                    this.$message({
                                        type: 'waring',
                                        message: '暂无数据导出。'
                                    })
                                }
                            } else {
                                this.$message({
                                    type: 'error',
                                    message: res.data.message
                                })
                            }
                        })
                    }

                })
        },
        getDetail(row) {
            // this.$refs['sum-detail'].showOn(row.agent_id)
            this.$refs['settlementDetails'].show(row.agent_id)
        },
        tableSortChange(column) {
            this.sort_params = {
                sort_str: column.prop
            }
            if (column.order == 'ascending') {
                this.sort_params.sort_order = 'asc'
            } else if (column.order == 'descending') {
                this.sort_params.sort_order = 'desc'
            } else {
                this.sort_params = {}
            }
            this.getTableData()
        },
        pageChange(data) {
            this.per_page = data.perPage
            this.current_page = data.page
            this.getTableData()
        },
        getTableData() {
            let params = {
                page: this.current_page,
                perPage: this.per_page
            }
            params = {...params, ...this.sort_params, ...this.search_params}
            this.$axios.get('/api/settlement/settlement_statistics', {
                params: params
            }).then(res => {
                if (res.data.code == 200) {
                    this.tableData = res.data.data
                    this.total = res.data.page.total
                } else {
                    this.$message({
                        type: 'error',
                        message: res.data.message
                    })
                }
            })
        },
        addFilterCondition(item) {
            let filterItem = {
                value: '',
                label: item.label,
                parameter: item.props,
                key: Date.now()
            }

            if (this.conditionForm.condition.length > 0) {
                let conditionlabels = []
                for (let i = 0; i < this.conditionForm.condition.length; i++) {
                    conditionlabels.push(this.conditionForm.condition[i].label)
                }
                let Check = conditionlabels.indexOf(item.label)
                Check == -1 ? this.conditionForm.condition.push(filterItem) : this.$message.error('请勿重复添加')
            } else {
                this.conditionForm.condition.push(filterItem)
            }

            this.showFilterCondition = false;
        },
        removeDomain(item) {
            let index = this.conditionForm.condition.indexOf(item)
            if (index !== -1) {
                this.conditionForm.condition.splice(index, 1)
            }
            if (item.label === '提交时间') {
                this.submitTime = []
            }
            let props = JSON.parse(JSON.stringify(this.conditionForm.condition))
            let params = {}
            props.forEach(v => {
                params[v.parameter] = v.value
            })
            if (params.created_at) {
                params.createdTime = params.created_at
                delete params.created_at
            }
            this.current_page = 1
            this.$refs['order-table'].clearSort()
            this.sort_params = {}
            this.search_params = {...params}
            this.getTableData()
        },
        submitsearch(formName) {
            let that = this
            this.$refs[formName].validate(valid => {
                if (valid) {
                    let props = JSON.parse(JSON.stringify(this.conditionForm.condition))
                    let params = {}
                    props.forEach(v => {
                        params[v.parameter] = v.value
                    })
                    if (params.created_at) {
                        params.createdTime = params.created_at
                        delete params.created_at
                    }
                    this.current_page = 1
                    this.$refs['order-table'].clearSort()
                    this.sort_params = {}
                    this.search_params = {...params}
                    this.getTableData()
                    this.showFilterCondition = false
                    this.showFilter = false
                }
            })
        },
        resetForm(formName) {
            this.$refs[formName].resetFields()
            this.conditionForm.condition.forEach(v => {
                if (v.value) {
                    v.value = null
                }
            });
            this.$refs['order-table'].clearSort()
            this.sort_params = {}
            this.search_params = {}
            this.$nextTick(() => {
                this.$refs[formName].clearValidate()
            })
            // this.getTableData()
            // this.showFilterCondition = false
            // this.showFilter = false
        },
        getAllAgent() {
            this.$axios.get('api/user/agent').then(res => {
                if (res.data.code == 200) {
                    this.agentOptions = res.data.data
                }
            }).catch(err => {
                this.$message({
                    type: "err",
                    message: err
                });
            });

            this.$axios.get('api/user/process').then(res => {
                if (res.data.code == 200) {
                    let arr = res.data.data;
                    this.processOptions = res.data.data
                }
            }).catch(err => {
                this.$message({
                    type: "err",
                    message: err
                });
            });
        },
    },

    watch: {

    }
}
</script>

<style lang="less" scoped>
.order-sum {
    height: 100%;
    /deep/.el-table {
		.img-wrap {
			display: flex;
            justify-content: center;
            > div {
                height: 23px;
            }
			.el-image {
                width: 23px;
				height: 23px;
			}
		}
	}
    /deep/.ivu-poptip-inner {
		min-width: 450px;
		// height: 300px;
		overflow-y: scroll;
	}

	/deep/.poptip-condition .ivu-poptip-inner {
		min-width: 180px;
	}

	.demo-dynamic {
		padding-left: 10px;

		.el-form-item {
			margin-bottom: 12px;
		}

		.el-input {
			width: 240px;
		}

		.el-date-editor {
			width: 240px;
		}

		.el-button {
			padding: 9px 15px;
			vertical-align: baseline;
		}

		.el-form-item__error {
			padding-top: 0;
		}
	}

	.poptip-condition {
		display: block;
		margin-top: 10px;

		.poptip-condition-item {
			line-height: 25px;
			cursor: pointer;
		}

		.poptip-condition-add {
			font-size: 14px;
		}
	}

	.btns {
		margin-top: 10px;
    }
    .el-select {
        width: 240px;
    }
}
</style>
